﻿using BaiTu.IQueueService.Providers;
using BaiTu.QueueEntity;
using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BaiTu.QueueService.Providers
{
    class RabbitMQProvider : IQueueProvider
    {
        public bool IsQueueExists(string queueName)
        {
            //是否后台监听线程已启动
            return false;
        }

        public void CreateQueue(string queueName)
        {
            string realQueueName = string.Format(QueueConfiguration.RabbitMQConfigInfo.QueueNameFormat, queueName);

            using (IModel channel = RabbitMQFactory.CreateRabbitMQChannel())
            {
                //申明相应的Exchange、Queue
                channel.ExchangeDeclare(realQueueName, "direct", true);
                channel.QueueDeclare(realQueueName, true, false, false, null);
            }
        }

        public void DeleteQueue(string queueName)
        {
            string realQueueName = string.Format(QueueConfiguration.RabbitMQConfigInfo.QueueNameFormat, queueName);

            using (IModel channel = RabbitMQFactory.CreateRabbitMQChannel())
            {
                //申明相应的Exchange、Queue
                channel.ExchangeDelete(realQueueName);
                channel.QueueDelete(realQueueName);
            }
        }

        public string SendMessage(string queueName, InnerMessageWrapper msg)
        {
            string msgID = "";
            string realQueueName = string.Format(QueueConfiguration.RabbitMQConfigInfo.QueueNameFormat, queueName);

            using (IModel channel = RabbitMQFactory.CreateRabbitMQChannel())
            {
                IBasicProperties bp = channel.CreateBasicProperties();
                if (!string.IsNullOrEmpty(msg.CorrelationID))
                    bp.CorrelationId = msg.CorrelationID;
                msgID = bp.CorrelationId;
                byte[] body = Common.Helpers.XMLSerializationHelper.Serialize2Bytes_Protobuf<InnerMessageWrapper>(msg);
                channel.BasicPublish(realQueueName, realQueueName, bp, body);
            }
            return msgID;
        }

        public InnerMessageWrapper ReceiveMessage(string queueName, string relatedMsgId = "")
        {
            string realQueueName = string.Format(QueueConfiguration.RabbitMQConfigInfo.QueueNameFormat, queueName);

            using (IModel channel = RabbitMQFactory.CreateRabbitMQChannel())
            {
                //channel.BasicPublish(

                //channel.BasicPublish(realQueueName, realQueueName, null, body);
                //byte[] body = SerializeUtils.Serialize2Bytes_Protobuf<InnerMessageWrapper>(msg);
            }
            return null;
        }
    }
}
